﻿#include "Mesh.h"
#include "glad/glad.h"
#include "MeshData.h"
#include <stddef.h>

namespace DYGraphics
{
	Mesh::Mesh(): vao(-1), vbo(-1), ebo(-1) 
	{
		mData = new MeshData();
	}

	Mesh::Mesh(MeshData* pMeshData): mData(pMeshData), vao(-1), vbo(-1), ebo(-1) { }

	Mesh::~Mesh()
	{
		if (vao != -1) glDeleteVertexArrays(1, &vao);
		if (vbo != -1) glDeleteBuffers(1, &vbo);
		if (ebo != -1) glDeleteBuffers(1, &ebo);

		if (mData != nullptr)
		{
			mData->Destroy();
			mData = nullptr;
		}
	}

	void Mesh::Apply()
	{
		glGenVertexArrays(1, &vao);
		glGenBuffers(1, &vbo);
		glGenBuffers(1, &ebo);

		glBindVertexArray(vao);

		glBindBuffer(GL_ARRAY_BUFFER, vbo);
		glBufferData(GL_ARRAY_BUFFER, mData->vertexCnt * sizeof(Vertex), &(mData->vertices[0]), GL_STATIC_DRAW);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, mData->indiceCnt * sizeof(unsigned int), &(mData->indices[0]), GL_STATIC_DRAW);

		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));

		glEnableVertexAttribArray(1);
		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal));

		glEnableVertexAttribArray(2);
		glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, tangent));

		glEnableVertexAttribArray(3);
		glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texcoord));

		glBindVertexArray(0);
	}

	void Mesh::Draw()
	{
		glBindVertexArray(vao);
		glDrawElements(GL_TRIANGLES, mData->indiceCnt, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);
	}
}